<template>
  <p-card :bordered="false">
    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <p-button @click="handleAdd" type="primary" icon="plus">新增</p-button>
      <template
        v-if="cgButtonList && cgButtonList.length > 0"
        v-for="(item, index) in cgButtonList"
      >
        <p-button
          v-if="
            item.optType == 'js' &&
            (item.groupTag == null || item.groupTag == '')
          "
          :key="'cgbtn' + index"
          @click="cgButtonJsHandler(item.buttonCode)"
          type="primary"
          :icon="item.buttonIcon"
          >{{ item.buttonName }}</p-button
        >
        <p-button
          v-else-if="
            item.optType == 'action' &&
            (item.groupTag == null || item.groupTag == '')
          "
          :key="'cgbtn' + index"
          @click="cgButtonActionHandler(item.buttonCode)"
          type="primary"
          :icon="item.buttonIcon"
          >{{ item.buttonName }}</p-button
        >
      </template>

      <!-- 高级查询区域 -->
      <j-super-query
        :fieldList="fieldList"
        ref="superQueryModal"
        @handleSuperQuery="handleSuperQuery"
      ></j-super-query>
      <p-dropdown v-for="(item, index) in groupTag" :key="index">
        <p-button>
          {{ item.name }}
          <p-icon type="down" />
        </p-button>
        <p-menu slot="overlay">
          <template v-for="(items, indexs) in item.data">
            <p-menu-item
              v-if="items.optType == 'js'"
              :key="indexs"
              @click="cgButtonJsHandler(items.buttonCode)"
            >
              <p-icon :type="items.buttonIcon" />{{ items.buttonName }}
            </p-menu-item>
            <p-menu-item
              v-else-if="items.optType == 'action'"
              :key="indexs"
              @click="cgButtonActionHandler(items.buttonCode)"
            >
              <p-icon :type="items.buttonIcon" />{{ items.buttonName }}
            </p-menu-item>
          </template>
        </p-menu>
      </p-dropdown>
      <p-dropdown v-if="selectedRowKeys.length > 0">
        <p-menu slot="overlay">
          <p-menu-item key="1" @click="batchDel"
            ><p-icon type="delete" />删除</p-menu-item
          >
        </p-menu>
        <p-button style="margin-left: 8px">
          批量操作 <p-icon type="down"
        /></p-button>
      </p-dropdown>
    </div>
    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择
        <a style="font-weight: 600">{{ selectedRowKeys.length }}</a
        >项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>

        <span style="float: right">
          <a @click="handleExportXls('工序标签维护')"
            ><p-icon type="download" />导出</a
          >
          <p-divider type="vertical" />
          <a @click="loadData()"><p-icon type="sync" />刷新</a>
          <p-divider type="vertical" />
          <p-popover
            title="自定义列"
            trigger="click"
            placement="leftBottom"
            :overlay-style="getWidth"
          >
            <template slot="content">
              <p-checkbox-group
                @change="onColSettingsChange"
                v-model="settingColumns"
                :defaultValue="settingColumns"
              >
                <p-row>
                  <template v-for="(item, index) in defColumns">
                    <template
                      v-if="
                        item.key != 'rowIndex' && item.dataIndex != 'action'
                      "
                    >
                      <p-col :span="12"
                        ><p-checkbox :value="item.dataIndex">{{
                          item.title
                        }}</p-checkbox></p-col
                      >
                    </template>
                  </template>
                </p-row>
              </p-checkbox-group>
            </template>
            <a><p-icon type="setting" />自定义列</a>
          </p-popover>
        </span>
      </div>
      <p-table
        ref="table"
        size="middle"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{
          fixed: true,
          selectedRowKeys: selectedRowKeys,
          onChange: onSelectChange,
        }"
        @change="handleTableChange"
      >
        <span slot="action" slot-scope="text, record">
          <a @click="handleEdit(record)">编辑</a>

          <p-divider type="vertical" />
          <p-popconfirm
            title="确定删除吗?"
            @confirm="() => handleDelete(record.id)"
          >
            <a style="color:red">删除</a>
          </p-popconfirm>
        </span>
      </p-table>
    </div>
    <!-- table区域-end -->
    <AgingruleModule
      ref="modalForm"
      :EnhanceJS="EnhanceJS"
      @ok="modalFormOk"
    ></AgingruleModule>
    <!-- 弹出窗 -->
    <Fx-compontens-modal
      @ok="modalFormOk"
      ref="modalCompon"
      :getList="queryInfo"
      :title="title"
      :dictOptions="dictOptions"
    ></Fx-compontens-modal>
  </p-card>
</template>

<script>
import { JeecgListMixin } from "@/mixins/JeecgListMixin";
import { api } from "@/api/manage";
import JSuperQuery from "@/components/jeecg/JSuperQuery.vue";
import { filterObj, timestampToDatetime } from "@/utils/util";
import AgingruleModule from "./modules/AgingruleModule";

import Vue from "vue";
import {
  initDictOptions,
  filterMultiDictText,
} from "@/components/dict/JDictSelectUtil";
import ButtonExpHandler from "@/components/jeecgbiz/modules/ButtonExpHandler";
import { postAction, getAction, deleteAction } from "@/api/manage";
import FxCompontensModal from "@/components/jeecgbiz/FxCompontensModal";
//高级查询modal需要参数
const superQueryFieldList = [
  {
    value: "productTypeName",
    text: "产品类别",
    type: "string",
  },
  {
    value: "productCode",
    text: "产品编码",
    type: "string",
  },
  {
    value: "productName",
    text: "产品名称",
    type: "String",
  },
  {
    value: "agingTime",
    text: "老化时长",
    type: "string",
  },
];

export default {
  name: "MesBcProcessLabelList",
  mixins: [JeecgListMixin],
  components: {
    JSuperQuery,
    FxCompontensModal,
    AgingruleModule,
  },
  data() {
    return {
      fieldList: superQueryFieldList,
      superQueryFlag: false,
      superQueryParams: "",
      cgButtonLinkList: [],
      title: "", //存表名
      EnhanceJS: "",
      cgButtonList: [],
      groupTag: [],
      queryInfo: [],
      code: "",
      // 表头
      columns: [],
      //列设置
      settingColumns: [],
      //列定义
      defColumns: [
        {
          title: "序号",
          dataIndex: "",
          key: "rowIndex",
          width: 60,
          align: "center",
          customRender: function (t, r, index) {
            return parseInt(index) + 1;
          },
        },
        {
          title: "产品类别",
          align: "center",
          dataIndex: "productTypeName",
        },
        {
          title: "产品编码",
          align: "center",
          dataIndex: "productCode",
        },
        {
          title: "产品名称",
          align: "center",
          dataIndex: "productName",
        },
        {
          title: "老化时长(分钟)",
          align: "center",
          dataIndex: "agingTime",
        },
        {
          title: "操作",
          dataIndex: "action",
          align: "center",
          scopedSlots: { customRender: "action" },
        },
      ],
      url: {
        list: "/mes-manufacture/mfAgingRules/list", //获得老化列表
        delete: "/mes-manufacture/mfAgingRules", //删除老化规则
        deleteBatch: "/mes-code/mesBcProcessLabel",
        exportXlsUrl: "/mes-code/mesBcProcessLabel/export",
        // importExcelUrl: '/mes-code/auto/mesBcProcessLabel/importExcel',
        getColumns: "/mes-code/online/cgform/api/getColumns/",
        buttonAction: "/mes-code/online/cgform/api/doButton",
      },
      dictOptions: {},
    };
  },
  computed: {
    importExcelUrl: function () {
      return `${api.test}${this.url.importExcelUrl}`;
    },
    getWidth: function () {
      if (this.defColumns.length > 14) {
        return { width: "500px" };
      }
    },
    tableScroll: function () {
      if (this.columns.length > 13) {
        return { x: this.columns.length * 150 - 450 };
      }
    },
  },
  created() {
    // this.initButtonList();
    this.initColumns();
  },

  methods: {
    initColumns() {
      //权限过滤（列权限控制时打开，修改第二个参数为授权码前缀）
      //this.defColumns = colAuthFilter(this.defColumns,'testdemo:');

      var key = this.$route.name + ":colsettings";
      let colSettings = Vue.ls.get(key);
      if (colSettings == null || colSettings == undefined) {
        let allSettingColumns = [];
        this.defColumns.forEach(function (item, i, array) {
          allSettingColumns.push(item.dataIndex);
        });
        this.settingColumns = allSettingColumns;
        this.columns = this.defColumns;
      } else {
        this.settingColumns = colSettings;
        const cols = this.defColumns.filter((item) => {
          if (item.key == "rowIndex" || item.dataIndex == "action") {
            return true;
          }
          if (colSettings.includes(item.dataIndex)) {
            return true;
          }
          return false;
        });
        this.columns = cols;
      }
    },
    //列设置更改事件
    onColSettingsChange(checkedValues) {
      var key = this.$route.name + ":colsettings";
      Vue.ls.set(key, checkedValues, 7 * 24 * 60 * 60 * 1000);
      this.settingColumns = checkedValues;
      const cols = this.defColumns.filter((item) => {
        if (item.key == "rowIndex" || item.dataIndex == "action") {
          return true;
        }
        if (this.settingColumns.includes(item.dataIndex)) {
          return true;
        }
        return false;
      });
      this.columns = cols;
    },

    //高级查询方法
    // handleSuperQuery(arg) {
    //   if (!arg) {
    //     this.superQueryParams = "";
    //     this.superQueryFlag = false;
    //   } else {
    //     this.superQueryFlag = true;
    //     this.superQueryParams = JSON.stringify(arg);
    //   }
    //   this.loadData();
    // },
    // 获取查询条件
    // getQueryParams() {
    //   let sqp = {};
    //   if (this.superQueryParams) {
    //     sqp["superQueryParams"] = encodeURI(this.superQueryParams);
    //   }
    //   var param = Object.assign(sqp, this.queryParam, this.isorter);
    //   param.field = this.getQueryField();
    //   param.pageNo = this.ipagination.current;
    //   param.limit = this.ipagination.pageSize;
    //   return filterObj(param);
    // },
    initDictConfig() {},
    //新增调取数据字典
    handleAdd: function () {
      this.$refs.modalForm.add();
      this.$refs.modalForm["getRuleCodeValue"]
        ? this.$refs.modalForm.getRuleCodeValue()
        : "";
      this.$refs.modalForm.title = "新增";
      this.$refs.modalForm.disableSubmit = false;
    },
    showLinkButton(item, record) {
      let btn = new ButtonExpHandler(item.exp, record);
      return btn.show;
    },
    cgButtonJsHandler(buttonCode) {
      if (this.EnhanceJS[buttonCode]) {
        this.EnhanceJS[buttonCode](this);
      }
    },
    cgButtonActionHandler(buttonCode) {
      //处理自定义button的 需要配置该button自定义sql
      if (!this.selectedRowKeys || this.selectedRowKeys.length == 0) {
        this.$message.warning("请先选中一条记录");
        return false;
      }
      if (this.selectedRowKeys.length > 1) {
        this.$message.warning("请只选中一条记录");
        return false;
      }
      let params = {
        formId: this.code,
        buttonCode: buttonCode,
        dataId: this.selectedRowKeys[0],
      };
      console.log("自定义按钮请求后台参数：", params);
      postAction(this.url.buttonAction, params).then((res) => {
        if (res.success) {
          this.loadData();
          this.$message.success("处理完成!");
        } else {
          this.$message.warning("处理失败!");
        }
      });
    },
    cgButtonLinkHandler(record, buttonCode, optType) {
      if (optType == "js") {
        if (this.EnhanceJS[buttonCode]) {
          this.EnhanceJS[buttonCode](this, record);
        }
      } else if (optType == "action") {
        let params = {
          formId: this.code,
          buttonCode: buttonCode,
          dataId: record.id,
        };
        console.log("自定义按钮link请求后台参数：", params);
        postAction(this.url.buttonAction, params).then((res) => {
          if (res.success) {
            this.loadData();
            this.$message.success("处理完成!");
          } else {
            this.$message.warning("处理失败!");
          }
        });
      }
    },
    handleDelete: function (id) {
      if (!this.url.delete) {
        this.$message.error("请设置url.delete属性!");
        return;
      }
      var that = this;
      deleteAction(that.url.delete + `/${id}`, {}).then((res) => {
        if (res.success) {
          that.$message.success(res.msg);
          that.loadData();
        } else {
          that.$message.warning(res.msg);
        }
      });
    },
    batchDel: function () {
      if (!this.url.deleteBatch) {
        this.$message.error("请设置url.deleteBatch属性!");
        return;
      }
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning("请选择一条记录！");
      } else {
        var ids = "";
        for (var a = 0; a < this.selectedRowKeys.length; a++) {
          ids += this.selectedRowKeys[a] + ",";
        }
        var that = this;
        this.$confirm({
          title: "确认删除",
          content: "是否删除选中数据?",
          onOk: function () {
            that.loading = true;
            deleteAction(that.url.deleteBatch + `/${ids}`, {})
              .then((res) => {
                if (res.success) {
                  that.$message.success(res.msg);
                  that.loadData();
                  that.onClearSelected();
                } else {
                  that.$message.warning(res.msg);
                }
              })
              .finally(() => {
                that.loading = false;
              });
          },
        });
      }
    },
  },
};
</script>
<style>
</style>